<template>
  <Dialog v-model="dialogVisible" title="打开模版" width="800px" max-height="600px" @close="close">
    <el-check-tag
      class="m-5px text-15px"
      v-for="(item, index) in keywords"
      :key="item.id"
      type="info"
      round
      size="large"
      :checked="item.checked"
      @change="onchange(index)"
    >
      {{ item.labelname }}
    </el-check-tag>

    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as UserApi from '@/api/system/user'

import download from '@/utils/download'
import * as BiaoqianApi from '@/api/system/biaoqian'
// import * as label from '@/api/infra/label'
defineOptions({ name: 'SystemUserImportForm' })

const message = useMessage() // 消息弹窗
const keywords = ref([]) // 关键字数组
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/system/user/import'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const updateSupport = ref(0) // 是否更新已经存在的用户数据
// 定义两个自定义事件 (需要时使用 emits触发)
const emits = defineEmits(['success', 'getTreeList'])

// 标签查询
const listBiaoqianApiParams = reactive({
  nameList: '',
  labelname: ''
})
const isFlag = ref(false)
const index = ref(0)
/** 打开弹窗 */
const open = async (value = false, ind = 0) => {
  isFlag.value = value
  index.value = ind
  const data = await BiaoqianApi.selectTreeName()
  keywords.value = data.map((item) => {
    return { ...item, checked: false }
  })
  dialogVisible.value = true
  // resetForm()
}
//  打开模版选择模版时的点击事件
const onchange = (value) => {
  if (isFlag.value) keywords.value.forEach((it) => (it.checked = false))
  keywords.value[value].checked = !keywords.value[value].checked
}

/** 提交表单 */
const submitForm = async () => {
  listBiaoqianApiParams.nameList = keywords.value
    .filter((item) => item.checked)
    .map((it) => it.tamplateid)
    .join(';')

  // 触发父组件方法 再由父组件触发 子组件标签树形结构 方法 并传递参数
  // 关闭弹框
  emits('getTreeList', listBiaoqianApiParams)
  dialogVisible.value = false

  if (index.value == 1) {
    formData.value.tamplate = {
      label: keywords.value.find((item) => item.checked).labelname || '',
      value: keywords.value.find((item) => item.checked).tamplateid || ''
    }
  } else if (index.value == 2) {
    formData.value.tamplate2 = {
      label: keywords.value.find((item) => item.checked).labelname || '',
      value: keywords.value.find((item) => item.checked).tamplateid || ''
    }
  }

  console.log(formData.value, 'formData的值')
  // console.log(api)
}
defineExpose({ open }) // 对外暴露 open 方法，用于打开弹窗
// 获取 父组件 MergeForm.vue 中传过来的参数 formData
const formData = defineModel()
// const close = () => {
//   console.log(keywords.value.some((it) => it.checked))

//   if (!keywords.value.some((it) => it.checked)) return

// }
/** 文件上传成功 */
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  // 拼接提示语
  const data = response.data
  let text = '上传成功数量：' + data.createUsernames.length + ';'
  for (let username of data.createUsernames) {
    text += '< ' + username + ' >'
  }
  text += '更新成功数量：' + data.updateUsernames.length + ';'
  for (const username of data.updateUsernames) {
    text += '< ' + username + ' >'
  }
  text += '更新失败数量：' + Object.keys(data.failureUsernames).length + ';'
  for (const username in data.failureUsernames) {
    text += '< ' + username + ': ' + data.failureUsernames[username] + ' >'
  }
  message.alert(text)
  // 发送操作成功的事件
  emits('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

/** 下载模板操作 */
const importTemplate = async () => {
  const res = await UserApi.importUserTemplate()
  download.excel(res, '用户导入模版.xls')
}
</script>
